package com.qfedu.springmvc02.controller;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.springmvc02.entity.User;
import com.qfedu.springmvc02.response.Response;
import com.qfedu.springmvc02.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@Controller
@SessionAttributes({"user"})
public class LoginController {
    @Autowired
    UserService userService;

    @RequestMapping("login")
    public String login(User user,String code,Integer pageIndex, Model model, HttpServletRequest request){
        //获取
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (Objects.equals(code,captcha)){
            User login = userService.login(user.getName(), user.getPassword());
            if (Objects.nonNull(login)){
                model.addAttribute("user",user);
                if (Objects.isNull(pageIndex)){
                    pageIndex=1;
                }
                PageHelper.startPage(pageIndex, 5);
                List<User> users = userService.selectAll();
                PageInfo<User> pageInfo= new PageInfo<>(users);
                model.addAttribute("pageInfo",pageInfo);
                return "welcome";
            }else{
                model.addAttribute("error","用户名或密码错误");
            }
        }else {
            model.addAttribute("error","验证码错误");
        }

        return "index";
    }



    @RequestMapping("loginJson")
    @ResponseBody
    public Response<User> loginJson(User user, String code, Integer pageIndex, Model model, HttpServletRequest request){
        //获取
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (Objects.equals(code,captcha)){
            User login = userService.login(user.getName(), user.getPassword());
            if (Objects.nonNull(login)){
                model.addAttribute("user",user);
                if (Objects.isNull(pageIndex)){
                    pageIndex=1;
                }
                PageHelper.startPage(pageIndex, 5);
                List<User> users = userService.selectAll();
                PageInfo<User> pageInfo= new PageInfo<>(users);
                model.addAttribute("pageInfo",pageInfo);
                return Response.success(login);
            }else{
               return Response.fail(-1,"用户名或密码错误",null);
            }
        }else {
            return Response.fail(-1,"验证码错误",null);
        }
    }
}

